﻿using Aspose.Cells;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Aspose.Slides;



namespace HyEduOnline.Models
{
    public class OfficeHelper
    {
        /// <summary>
        /// office预览转换
        /// </summary>
        /// <param name="filePath">文件相对路径</param>
        /// <returns></returns>
        public static void ShowOfficeDoc(string filePath)
        {
            bool officeInternetView = currentSys.isShowMS;//是否使用互联网在线预览
            string hostName = HttpUtility.UrlPathEncode(currentSys.SysURL);//可以配置一下，如果有必要
            string viewUrl;

            string ext = Path.GetExtension(filePath);//扩展名 “.doc"


            if (ext == ".xls" || ext == ".xlsx" || ext == ".doc" || ext == ".docx" || ext == ".ppt" || ext == ".pptx")
            {
                if (officeInternetView)
                {
                    //返回一个微软在线浏览Office的地址，需要加上互联网域名或者公网IP地址
                    viewUrl = string.Format("http://view.officeapps.live.com/op/view.aspx?src={0}{1}", hostName, filePath);
                }
                else
                {
                    #region 动态第一次生成htm文件

                    string viewFile = filePath.Substring(0, filePath.LastIndexOf("/"));
                    string viewFilePath = viewFile.Replace("/UploadFile", "/ViewFile");

                    //检查本地Office文件是否存在，如不存在，先生成文件，然后返回路径供查看
                    string webPath = string.Format(viewFilePath+"/{0}.htm", Path.GetFileNameWithoutExtension(filePath));
                    string generateFilePath = System.Web.HttpContext.Current.Server.MapPath(webPath);
                    if (!(System.IO.File.Exists(generateFilePath)))
                    {
                        string templateFile = System.Web.HttpContext.Current.Server.MapPath(filePath);

                        if (ext == ".doc" || ext == ".docx")
                        {
                            Aspose.Words.Document doc = new Aspose.Words.Document(templateFile);
                            doc.Save(generateFilePath, Aspose.Words.SaveFormat.Html);
                        }
                        else if (ext == ".xls" || ext == ".xlsx")
                        {
                            Workbook workbook = new Workbook(templateFile);
                            workbook.Save(generateFilePath, SaveFormat.Html);
                        }
                        else if (ext == ".ppt" || ext == ".pptx")
                        {

                            templateFile = templateFile.Replace("/", "\\");
                            Presentation pres = new Presentation(templateFile);
                            pres.Save(generateFilePath, Aspose.Slides.Export.SaveFormat.Html);
                        }
                    }
                    #endregion                  
                }
            }
        }
    }
}